Python 使用 feedgen 生成 RSS Feed
介绍
博客的 RSS Feed 功能开通了,欢迎订阅!RSS Feed 能够让别人方便地订阅博客,是博客的重要功能。我的博客是通过静态生成器生成的,这个生成器是使用 Python 编写的。
因此需要给静态生成器添加 RSS Feed 功能。
feedgen 是 Python 下的 RSS Feed 生成库,非常简单易用,项目首页地址。
安装:pip install feedgen
使用
使用整体分为 3 步:
- 创建 Feed
- 添加条目
- 导出文件
这里以官方示例为例:
创建 Feed
from feedgen.feed import FeedGenerator
fg = FeedGenerator()
fg.id('http://lernfunk.de/media/654321')
fg.title('Some Testfeed')
fg.author( {'name':'John Doe','email':'john@example.de'} )
fg.link( href='http://example.com', rel='alternate' )
fg.logo('http://ex.com/logo.jpg')
fg.subtitle('This is a cool feed!')
fg.link( href='http://larskiesow.de/test.atom', rel='self' )
fg.language('en')
插入条目
fe = fg.add_entry()
fe.id('http://lernfunk.de/media/654321/1')
fe.title('The First Episode')
fe.link(href="http://lernfunk.de/feed")
文件导出
atomfeed = fg.atom_str(pretty=True) # Get the ATOM feed as string
rssfeed = fg.rss_str(pretty=True) # Get the RSS feed as string
fg.atom_file('atom.xml') # Write the ATOM feed to a file
fg.rss_file('rss.xml') # Write the RSS feed to a file
实际代码
我在项目中使用的实际代码如下:
def genFeed(self, ret):
"""
生成 RSS Feed
"""
fg = FeedGenerator()
fg.id('https://www.maxieewong.com')
fg.title('Maxiee Blog')
fg.author({'name': 'Maxiee', 'email': 'maxieewong@gmail.com'})
fg.link(href='https://www.maxieewong.com', rel='alternate')
ret.reverse()
host = 'https://www.maxieewong.com/{}.html'
for index, item in enumerate(ret):
fe = fg.add_entry()
fe.id(item['title'] + item['timestamp'])
fe.title(item['title'])
fe.updated(item['timestamp'])
fe.content(src=host.format(item['url']))
fe.link(href=host.format(item['url']))
fe.summary(item['comment'])
fg.atom_file(self.storage.getPath(
str(PATH_BLOG_SITE_OUTPUT.joinpath('atom.xml'))))